package com.dunqi.gpm.cangxi.home.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.WeekReport.Model.WeekChekModel;
import com.dunqi.gpm.cangxi.WeekReport.WeekChek.WeekCheckDetail.WeekCheckDetailFragment;
import com.dunqi.gpm.cangxi.WeekReport.WeekDetailControlerActivity;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseFragment;
import com.dunqi.gpm.cangxi.common.base.RecyclerAdapter;
import com.dunqi.gpm.cangxi.common.util.CommonUtil;
import com.dunqi.gpm.cangxi.common.util.SwipeUtil;
import com.dunqi.gpm.cangxi.common.view.RecyclerItemDecoration;
import com.dunqi.gpm.cangxi.home.activity.CompleteEarlyInfoActivity;
import com.dunqi.gpm.cangxi.home.activity.EarlyAuditDetailActivity;
import com.dunqi.gpm.cangxi.home.activity.EditRequestActivity;
import com.dunqi.gpm.cangxi.home.activity.ProjectProgressDetailsActivity;
import com.dunqi.gpm.cangxi.home.adapter.EarlyInfoAdapter;
import com.dunqi.gpm.cangxi.home.adapter.ProjectTimelineAdapter;
import com.dunqi.gpm.cangxi.home.bean.EarlyInfo;
import com.dunqi.gpm.cangxi.home.bean.Project;
import com.dunqi.gpm.cangxi.home.bean.ProjectTimeline;
import com.dunqi.gpm.cangxi.home.constance.Constance;
import com.dunqi.gpm.cangxi.home.widget.EmptyView;
import com.dunqi.gpm.cangxi.mine.util.UserUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

public class ProjectAllProgressFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;

    @BindViews({R.id.header_1, R.id.header_2, R.id.header_3})
    List<TextView> headers;

    @BindViews({R.id.recycler_1, R.id.recycler_2, R.id.recycler_3})
    List<RecyclerView> recyclerViews;
    Project project;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        project = (Project) arguments.getSerializable(Constance.PROJECT);
    }

    public static ProjectAllProgressFragment newInstance(Project project) {
        ProjectAllProgressFragment fragment = new ProjectAllProgressFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constance.PROJECT, project);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void refreshData(Bundle savedInstanceState) {
        net();
    }

    @Override
    protected void initUiAndListener() {
        setControler();
        swipeRefresh.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        net();
    }

    private void setControler() {
    }

    private void hintOther(int index) {
        if (recyclerViews.get(index).getVisibility() == View.VISIBLE) {
            recyclerViews.get(index).setVisibility(View.GONE);
        } else {
            for (RecyclerView view : recyclerViews) {
                view.setVisibility(View.GONE);
            }
            recyclerViews.get(index).setVisibility(View.VISIBLE);
        }
//        if (index < 2) {
//            headers.get(2).setLayoutParams(new LinearLayout.LayoutParams());
//        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_project_all_progress;
    }

    @OnClick({R.id.header_1, R.id.header_2, R.id.header_3})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.header_1:
                hintOther(0);
                break;
            case R.id.header_2:
                hintOther(1);
                break;
            case R.id.header_3:
                hintOther(2);
                break;
        }
    }

    private void net() {
        getEarlyInfo();
        getYB();
        getZB();
    }

    HashMap<String, String> parms = new HashMap<>();
    List<EarlyInfo> data_early = new ArrayList();
    private EarlyInfoAdapter adapter_early;

    //获取项目前期信息
    @SuppressLint("CheckResult")
    private void getEarlyInfo() {
        if (adapter_early == null) {
            recyclerViews.get(0).setLayoutManager(new LinearLayoutManager(context));
            recyclerViews.get(0).addItemDecoration(new RecyclerItemDecoration(1, RecyclerItemDecoration.VERTICAL));
            adapter_early = new EarlyInfoAdapter(data_early);
            recyclerViews.get(0).setAdapter(adapter_early);
            adapter_early.setEmptyView(new EmptyView(context));
            recyclerViews.get(0).addItemDecoration(new RecyclerItemDecoration(1, RecyclerItemDecoration.VERTICAL));
//            adapter_early.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//                @Override
//                public void onLoadMoreRequested() {
//
//                }
//            }, recyclerViews.get(0));
            //    0 创建
            //1 提交审批申请(实际启动)
            //2 完成审批(实际完成)
            adapter_early.setOnItemClickListener((adapter, view, position) -> {
                EarlyInfo item = data_early.get(position);

                EarlyAuditDetailActivity.start(getActivity(), item);
                if (true) {
                    return;
                }
                int stageStatus = item.getStageStatus();
                int levelType = UserUtil.getLevelType();
                if (HomeFragment.homeMenuId == 11) {
                    return;
                }
                if (levelType != 3) {
                    return;
                }
                String stageName = item.getStageName();
                long proAnnualPlanPreStageId = item.getProAnnualPlanPreStageId();
                if (stageStatus == 0) {
                    EditRequestActivity.start(getActivity(), proAnnualPlanPreStageId, stageName);
                }
                if (stageStatus == 1) {
                    CompleteEarlyInfoActivity.start(getActivity(), proAnnualPlanPreStageId, stageName);
                }
            });
        }

        long projectId = project == null ? null : project.getProjectId();
        parms.put(Constance.PROJECT_ID, String.valueOf(projectId));
        parms.put(Constance.PAGE, String.valueOf(page));

        //审核审批
        if (HomeFragment.homeMenuId == 9) {
            parms.put("stage_status", "1,2");
        }

        //申请
        if (HomeFragment.homeMenuId == 10) {
//            parms.put("stage_status", "1");
            parms.put("pro_annual_plan_id", String.valueOf(project.getProAnnualPlanId()));
//            parms.remove(Constance.PROJECT_ID);
        }

        ApiFactory.getInstance()
                .queryProjectPreStageList(parms)
                .compose(RxSchedulers.io_main())
                .subscribe(earlyInfoPage -> {
                    SwipeUtil.loadCompleted(swipeRefresh);
                    ArrayList<EarlyInfo> list = earlyInfoPage.getList();
                    if (page == 1) {
                        data_early.clear();
                    }
                    data_early.addAll(list);
                    // page++;
                    adapter_early.notifyDataSetChanged();

                    if (earlyInfoPage.isHasNextPage()) {
                        adapter_early.loadMoreComplete();
                    } else {
                        adapter_early.loadMoreEnd();
                    }
                }, throwable -> adapter_early.loadMoreFail());
    }

    private ProjectTimelineAdapter adapter_yue;
    List<ProjectTimeline> data_yue = new ArrayList<>();

    //获取项目月报信息
    @SuppressLint("CheckResult")
    private void getYB() {
        if (adapter_yue == null) {
            recyclerViews.get(1).setLayoutManager(new LinearLayoutManager(context));
            adapter_yue = new ProjectTimelineAdapter(context, data_yue);
            recyclerViews.get(1).setAdapter(adapter_yue);
            swipeRefresh.setOnRefreshListener(this);
//            adapter_yue.setOnLoadMoreListener(this, recyclerViews.get(1));
            adapter_yue.setOnItemClickListener((adapter, view, position) -> {
                ProjectProgressDetailsActivity.start((Activity) context, data_yue.get(position).getProPlanProgressId());
            });
            adapter_yue.setEmptyView(new EmptyView(context));
        }
        ApiFactory.getInstance()
                .queryProjectProgressList(project == null ? null : project.getProjectId(), page)
                .compose(RxSchedulers.io_main())
                .subscribe(projectTimelinePage -> {
                    SwipeUtil.loadCompleted(swipeRefresh);
                    ArrayList<ProjectTimeline> list = projectTimelinePage.getList();
                    if (page == 1) {
                        data_yue.clear();
                    }
                    data_yue.addAll(list);
                    adapter_yue.notifyDataSetChanged();
                    if (projectTimelinePage.isHasNextPage()) {
                        adapter_yue.loadMoreComplete();
                    } else {
                        adapter_yue.loadMoreEnd();
                    }
                    //  page++;
                }, throwable -> {
                    adapter_yue.loadMoreFail();
                    SwipeUtil.loadCompleted(swipeRefresh);
                });
    }

    List<WeekChekModel> weekChekModels = new ArrayList<>();
    WeekCheckAdapter adapter_weekcheck;

    //获取项目周报信息
    @SuppressLint("CheckResult")
    private void getZB() {
        if (adapter_weekcheck == null) {
            recyclerViews.get(2).setLayoutManager(new LinearLayoutManager(context));
            adapter_weekcheck = new WeekCheckAdapter(getActivity(), weekChekModels);
            recyclerViews.get(2).setAdapter(adapter_weekcheck);
            swipeRefresh.setOnRefreshListener(this);
//            adapter_yue.setOnLoadMoreListener(this, recyclerViews.get(1));
            adapter_weekcheck.setOnItemClickListener((adapter, view, position) -> {
                Intent mIntent = new Intent(getActivity(), WeekDetailControlerActivity.class);
                mIntent.putExtra("object", weekChekModels.get(position));
                mIntent.putExtra("flag_checktype", WeekCheckDetailFragment.LookInfo);
                mIntent.putExtra("type", 4);
                startActivity(mIntent);
            });
            adapter_weekcheck.setEmptyView(new EmptyView(context));
        }
//        @Field("device_id") String device_id, @Field("projectName") String projectName, @Field("resp_org_id") String resp_org_id
        ApiFactory.getInstance()
                .projectWeeklyReportReviewList(CommonUtil.getDeviceId(), project.getProjectName(), project.getRespOrgId() + "")
                .compose(RxSchedulers.io_main())
                .subscribe(projectTimelinePage -> {
                    SwipeUtil.loadCompleted(swipeRefresh);
                    ArrayList<WeekChekModel> list = projectTimelinePage.getList();
                    if (page == 1) {
                        weekChekModels.clear();
                    }
                    weekChekModels.addAll(list);
                    adapter_weekcheck.notifyDataSetChanged();
                    if (projectTimelinePage.isHasNextPage()) {
                        adapter_weekcheck.loadMoreComplete();
                    } else {
                        adapter_weekcheck.loadMoreEnd();
                    }
                    //  page++;
                }, throwable -> {
                    adapter_weekcheck.loadMoreFail();
                    SwipeUtil.loadCompleted(swipeRefresh);
                });
    }

    class WeekCheckAdapter extends RecyclerAdapter<WeekChekModel> {

        int[] drawablesRes = new int[5];
        int[] colors = new int[5];
        String[] status = {"未填写", "进展顺利", "基本正常", "进度滞后", "申请结项"};
        String[] audit_state = {"待汇报", "创建", "待审核", "审核通过", "审核未通过", "待结项", "已结项"};

//    0 未填写
//1 进展顺利（绿灯）
//            2 基本正常（黄灯）
//            3 进度滞后（红灯）
//            4 申请结项

        public WeekCheckAdapter(Context context, @Nullable List<WeekChekModel> data) {
            super(R.layout.item_week_check_simple, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final WeekChekModel item) {
            Integer status = item.getReportStatus();
            helper.setText(R.id.item_audit_status, status == null ? "未审核" : status == 3 ? "审核不通过" : "审核通过");

            helper.setText(R.id.my_item_repotrt_week_times, item.getProjectReportWeekly().getWeeks() + "");
            helper.setText(R.id.item_report_content, item.getReportContext());
            helper.setText(R.id.item_audit_contentv, item.getAuditRemark());
        }
    }
}